package com.hjx.windowtool.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class XiaoShuoTest2 {
	public static String userAgent = "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-CN; MI 8 Build/OPM1.171019.026) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.108 UCBrowser/12.4.0.1020 Mobile Safari/537.36";
	public static void main(String[] args) throws Exception {
		String dir="D:\\git\\windowtool\\windowtool\\work\\book\\网游之时停6小时";
		if(!new File(dir).exists()||!new File(dir).isDirectory()) {
			new File(dir).mkdirs();
		}
		
//		List<String> listUrls=new ArrayList<String>();
//		List<String> listTitles=new ArrayList<>();
//		int page=1;
//		while (true) {
//			try {
//				List<String> listTempUrls=new ArrayList<String>();
//				List<String> listTempTitles=new ArrayList<>();
//				Connection conn = Jsoup.connect("https://wap.dulaidw.com/wapbook-147995_"+page+"/");
//				conn.header("User-Agent", userAgent);
//				Document d = conn.get();
//				Elements select = d.select(".chapter");
//				if (select.text().contains("无章节")) {
//					break;
//				}
//				Elements children = select.get(0).children();
//				for (Element element : children) {
//					Element child = element.child(0);
//					String attr = child.attr("abs:href");
//					System.out.println(attr);
//					listTempUrls.add(attr);
//					listTempTitles.add(child.text());
//				}
//				page++;
//				listUrls.addAll(listTempUrls);
//				listTitles.addAll(listTempTitles);
//				Thread.sleep(1000);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		System.out.println(listUrls.size());
//		Files.write(Paths.get(dir+"//url.text"), listUrls);
//		Files.write(Paths.get(dir+"//titel.text"), listTitles);
		
		
//		loadBookContentDulaidw(dir);
		
		packageChm(dir,"网游之时停6小时");
		
//		downloadImage("","","");
	}

	/**
	 * @param dir
	 * @throws IOException
	 */
	public static void loadBookContentDulaidw(String dir) throws IOException {
		List<String> list = Files.readAllLines(Paths.get(dir+"//url.text"));
		for (int i = 0; i < list.size(); i++) {
			try {
				String url = list.get(i);
				System.out.println(i+"==="+url);
				Connection conn = Jsoup.connect(url);
				conn.header("User-Agent",userAgent);
				Document d = conn.get();
//				System.out.println(d);
				Elements select = d.select(".imagecontent");
				if(select.size()>0) {
					String attr = select.attr("src");
					System.out.println(attr);
					downloadImage(attr, dir+"//"+i+".gif", "https://wap.dulaidw.com/wapbook-147995-35931049/");
				}else {
					select = d.select("#nr");
//					System.out.println(select);
					Elements tagName = select.select("#txt");
					List<String> listContents=new ArrayList<>();
					for (Element element : tagName) {
						String html = element.html().replaceAll("&nbsp;", " ");
						String[] split = html.split("<br>");
						for (String string : split) {
							if(StrUtil.isEmpty(string)) {
								continue;
							}
							listContents.add(string);
						}
					}
					Files.write(Paths.get(dir+"//"+i+".txt"), listContents);
				}
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
				i--;
			}
		}
	}

	/**
	 * @param dir
	 * @param fileName 
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 */
	public static String packageChm(String dir, String name) throws IOException, UnsupportedEncodingException {
		for (int i = 0; i < 10000; i++) {
			File gif = new File(dir, i+".gif");
			File txt = new File(dir, i+".txt");
			if (gif.exists()&&txt.exists()) {
				txt.delete();
			}
		}
		File[] files = new File(dir).listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".txt")||pathname.getName().endsWith(".gif");
			}
		});
		List<String> listTitles = Files.readAllLines(Paths.get(dir+"//titel.text"));
		List<File> listAllFiles = Arrays.asList(files);
		listAllFiles.sort(new Comparator<File>() {
			@Override
			public int compare(File o1, File o2) {
				Integer i1 = Integer.valueOf(o1.getName().substring(0, o1.getName().indexOf(".")));
				Integer i2 = Integer.valueOf(o2.getName().substring(0, o2.getName().indexOf(".")));
				return i1.compareTo(i2);
			}
		});
		String oldDir=dir;
		for (int i = 0; i < listTitles.size(); i+=2000) {
			int min = Math.min(i+2000, listTitles.size());
			List<File> listFiles = listAllFiles.subList(i, min);
			System.out.println(listFiles);
			String fileName=name+"_"+i+"-"+min;
			StringBuffer indexSb = new StringBuffer();
			List<String> listFileNames = new ArrayList<>();
			List<String> listhhcNames = new ArrayList<>();
			String contentTemp = new String(Files.readAllBytes(Paths.get("test.html")));
			new File(oldDir,fileName).mkdirs();
			dir=new File(oldDir,fileName).getAbsolutePath();
			for (File file : listFiles) {
				if (!new File(dir,file.getName()).exists()) {
					Files.copy(file.toPath(), new File(dir, file.getName()).toPath());
				}
				Integer i1 = Integer.valueOf(file.getName().substring(0, file.getName().indexOf(".")));
				StringBuffer page = new StringBuffer();
				if (i1 > 0) {
					page.append("<a id=\"prev\" href=\"" + (i1 - 1) + ".html\">上一页</a>&nbsp;&nbsp;");
				}
				page.append("<a href=\"index.html\">目录</a>&nbsp;&nbsp;");
				if (i1 < listTitles.size()) {
					page.append("<a id=\"next\" href=\"" + (i1 + 1) + ".html\">下一页</a>");
				}
				if (file.getName().endsWith(".txt")) {
					List<String> lines = Files.readAllLines(file.toPath());
					StringBuffer sb = new StringBuffer();
					for (String string : lines) {
						if (string==null||string.trim().isEmpty()) {
							continue;
						}
						sb.append(string.replaceAll(" ", "&nbsp;"));
						sb.append("<br>");
					}
					String replace = contentTemp.replace("{title}", listTitles.get(i1)).replace("{content}", sb.toString()).replace("{page}", page);
					Files.write(Paths.get(dir + "//" + i1 + ".html"), replace.getBytes("UTF-8"));
				} else {
					StringBuffer sb = new StringBuffer();
					sb.append("<img style=\"width: 100%;\" src=\"" + file.getName() + "\"/>");
					String replace = contentTemp.replace("{title}", listTitles.get(i1)).replace("{content}", sb.toString()).replace("{page}", page);
					Files.write(Paths.get(dir + "//" + i1 + ".html"), replace.getBytes("UTF-8"));
				}
				indexSb.append("<div ><a href=\"" + i1 + ".html\">" + listTitles.get(i1) + "</a> </div>");
				listFileNames.add(i1 + ".html");
				listhhcNames.add("<LI><OBJECT type=\"text/sitemap\"><param name=\"Name\" value=\"" + listTitles.get(i1) + "\"><param name=\"Local\" value=\"" + i1 + ".html\"></OBJECT>");
			}
			String indexTemp = new String(Files.readAllBytes(Paths.get("test2.html")));
			String replace = indexTemp.replace("{content}", indexSb.toString());
			String indexHtml = min+"index.html";
			Files.write(Paths.get(dir + "//"+indexHtml), replace.getBytes("UTF-8"));
			listFileNames.add(indexHtml);
			String hhc=name+min+".hhc";
			List<String> listhhp = new ArrayList<>();
			listhhp.add("[OPTIONS]");
			listhhp.add("Compatibility=1.1 or later");
			listhhp.add("Compiled file=" + fileName + ".chm");
			listhhp.add("Contents file="+hhc);
			listhhp.add("Default topic="+indexHtml);
			listhhp.add("Display compile progress=No");
			listhhp.add("Language=0x804 中文(简体，中国)");
			listhhp.add("");
			listhhp.add("");
			listhhp.add("[FILES]");
			listhhp.addAll(listFileNames);
			listhhp.add("");
			listhhp.add("[INFOTYPES]");
			String hhp=name+min+".hhp";
			write(Paths.get(dir + "//"+hhp).toFile(), listhhp,"GBK");
			List<String> listhhc = new ArrayList<>();
			listhhc.add(
					"<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\"><HTML><HEAD><meta name=\"GENERATOR\" content=\"Microsoft&reg; HTML Help Workshop 4.1\"><!-- Sitemap 1.0 --></HEAD><BODY><OBJECT type=\"text/site properties\"><param name=\"ImageType\" value=\"Folder\"></OBJECT><UL>");
			listhhc.add("<LI><OBJECT type=\"text/sitemap\"><param name=\"Name\" value=\"首页\"><param name=\"Local\" value=\""+indexHtml+"\"></OBJECT>");
			listhhc.addAll(listhhcNames);
			listhhc.add("</UL></BODY></HTML>");
//			Files.write(Paths.get(dir + "//"+hhc), listhhc, Charset.forName("GBK"));
			write(new File(dir,hhc), listhhc, "GBK");
			
			Runtime.getRuntime().exec(System.getProperty("user.dir") + "//hhc.exe " + dir + "//"+hhp);
		}
		return oldDir;
	}
	
	public static void write(File file,List<String> list,String cs) throws FileNotFoundException, UnsupportedEncodingException {
		try(PrintWriter pw=new PrintWriter(file, "GBK")) {
			for (String string : list) {
				pw.println(string);
				pw.flush();
			}
		} finally{
			
		}
	}

	/**
	 * @throws IOException
	 * @throws MalformedURLException
	 */
	public static void downloadImage(String url,String save,String referer) throws IOException, MalformedURLException {
		if(StrUtil.isEmpty(url)||StrUtil.isEmpty(save)) {
			return;
		}
		HttpURLConnection connhttp = (HttpURLConnection) new URL(url).openConnection();
		connhttp.setDoInput(true);
		connhttp.setConnectTimeout(20000);
		connhttp.setReadTimeout(60000);
		connhttp.setRequestProperty("User-Agent",userAgent);
		if (!StrUtil.isEmpty(referer)) {
			connhttp.setRequestProperty("Referer", referer);
		}
		connhttp.connect();
		System.out.println(connhttp.getContentLength());
		InputStream is = connhttp.getInputStream();
		ByteBuffer bb=ByteBuffer.allocate(connhttp.getContentLength());
		byte[] bs = new byte[1024];
		int read = -1;
		while((read = is.read(bs))!=-1) {
			bb.put(bs, 0, read);
		}
		Path path = Paths.get(save);
		path.toFile().getParentFile().mkdirs();
		Files.write(path, bb.array());
	}
}
